package com.leonzhangxf.ioc.bean.impl;

import com.leonzhangxf.ioc.bean.CommonDependencyService;
import com.leonzhangxf.ioc.bean.HelloWorldMessage;
import com.leonzhangxf.ioc.bean.HelloWorldService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * A simple default implement by {@link HelloWorldService}.
 * <p>
 * The action need to be done upon the bean initialization could not just by implement
 * the interface {@link InitializingBean}, but also could be implemented by annotation
 * {@link javax.annotation.PostConstruct}.
 * So as the {@link org.springframework.beans.factory.DisposableBean} and
 * {@link javax.annotation.PreDestroy}.
 *
 * @author leonzhangxf
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DefaultHelloWorldServiceImpl implements HelloWorldService {

    @NonNull
    private final CommonDependencyService commonDependencyService;

    @Setter(onMethod_ = {@HelloWorldMessage})
    private String messageKey = "messageKey";

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        System.out.println(String.format("%s has bean initialized and this is afterPropertiesSet " +
                "method invoke commonly for properties check.",
            DefaultHelloWorldServiceImpl.class.getName()));
    }

    @Override
    public void helloWorld(OutputStream outputStream) throws IOException {
        outputStream.write("EnableHello World\n".getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        commonDependencyService.checkDependency();
    }

    @Override
    public void helloWorld() {
        System.out.println(String.format("The hello world bean message is %s.", this.messageKey));
    }
}
